package com.cykj.web.controller.posbiz;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.utils.date.DateUtil;
import com.cykj.pos.domain.*;
import com.cykj.pos.mapper.BizPosMachineStatusRecordsMapper;
import com.cykj.pos.mapper.UnFailureActiveTemplateMapper;
import com.cykj.pos.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/lkl" )
public class LklController {

    private final BizPosMachineStatusRecordsMapper bizPosMachineStatusRecordsMapper;
    private final IBizFeesChargedService bizFeesChargedService;
    private final IBizTransactionAmount bizTransactionAmount;
    private final IBizPosMachineService posMachineService;
    private final IBizMerchantInfoService bizMerchantInfoService ;

    @Resource
    private UnFailureActiveTemplateMapper unFailureActiveTemplateMapper;

    @Resource
    private IAizUnActiveRecordsService iAizUnActiveRecordsService;
    @PostMapping("/Binding")
    public AjaxResult binding(@RequestBody JSONObject jsonObject) throws ParseException {

        //BIND 绑定 UNBIND 解绑
        String type=jsonObject.getString("type");
        //外部商户编号
        String externalCustomerNo=jsonObject.getString("externalCustomerNo");
        //内部商户名称
        String customerName=jsonObject.getString("customerName");
        //法人姓名
        String legalName=jsonObject.getString("legalName");
        //机具SN
        String posSn=jsonObject.getString("posSn");
        //操作时间
        String operateTime=jsonObject.getString("operateTime");
        if("BIND".equals(type)){
            //查询设备信息
            BizPosMachine machine=posMachineService.selectPosBySnCode(posSn);
            BizMerchantInfo bizMerchantInfo=new BizMerchantInfo();
            bizMerchantInfo.setInfoCompleted("1");
            bizMerchantInfo.setAuditStatus("3");
            bizMerchantInfo.setPosCode(posSn);
            bizMerchantInfo.setMerchantName(legalName);
            bizMerchantInfo.setMerchantShortHand(customerName);
            bizMerchantInfo.setLegalPersonName(legalName);
            bizMerchantInfo.setMerchId(machine.getMerchId());
            bizMerchantInfo.setMerchantCode(externalCustomerNo);
            bizMerchantInfo.setRegisterTime(operateTime);
            bizMerchantInfo.setWhetherBinding("1");
            bizMerchantInfo.setOnLine("0");
            String deptId = bizMerchantInfoService.getDeptIdByPosCode(posSn);
            bizMerchantInfo.setDeptId(Long.valueOf(deptId));
            bizMerchantInfo.setChannel(machine.getChannel());
            BizChannel bizChannel = bizMerchantInfoService.getChannelDataByChannel(machine.getChannel());
            bizMerchantInfo.setChannelName(bizChannel.getChannelName());
            SysUser user = bizMerchantInfoService.getSysUserByMerchId(machine.getMerchId());
            bizMerchantInfo.setUserId(user.getInviteUserId());
            //存到自己的库里
            boolean save = bizMerchantInfoService.save(bizMerchantInfo);
            BizPosMachineStatusRecords bizPosMachineStatusRecords=new BizPosMachineStatusRecords();
            bizPosMachineStatusRecords.setSnCode(posSn);
            bizPosMachineStatusRecords.setMerchantId(externalCustomerNo);
            bizPosMachineStatusRecords.setTime(operateTime);
            bizPosMachineStatusRecords.setName(legalName);
            //新增激活表信息
            bizPosMachineStatusRecordsMapper.insertBizPosMachineStatusRecords(bizPosMachineStatusRecords);
//            if(machine.getTemp1() != null){
//                UnFailureActiveTemplate unFailureActiveTemplate = unFailureActiveTemplateMapper.selectById(machine.getTemp1());
//                if(unFailureActiveTemplate != null){
//                    // 增加一条未激活记录
//                    AizUnActiveRecords aizUnActiveRecords = new AizUnActiveRecords();
//                    aizUnActiveRecords.setMerchId(machine.getMerchId());
//                    aizUnActiveRecords.setMerchName(user.getNickName());
//                    aizUnActiveRecords.setMerchantCode(externalCustomerNo);
//                    aizUnActiveRecords.setMerchantName(legalName);
//                    aizUnActiveRecords.setMerchPhone(user.getPhonenumber());
//                    aizUnActiveRecords.setBindTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(operateTime));
//                    aizUnActiveRecords.setPosSn(posSn);
//                    aizUnActiveRecords.setTempDays(unFailureActiveTemplate.getDays());
//                    aizUnActiveRecords.setDays(0);
//                    aizUnActiveRecords.setCreateTime(DateUtil.getBaiDuTime());
//                    iAizUnActiveRecordsService.saveOrUpdate(aizUnActiveRecords);
//                }else{
//                    System.out.println("SN"+posSn+"绑定时未查询到未激活模板");
//                }
//            }
        }else if("UNBIND".equals(type)){
            bizMerchantInfoService.deleteBySN(posSn);
            //删除激活表信息
            bizPosMachineStatusRecordsMapper.deleteBizPosRecordsNew(posSn);
            //更新设备表激活状态
            bizPosMachineStatusRecordsMapper.updatePosMachine(posSn);
//            // 删除未激活模板数据
//            iAizUnActiveRecordsService.deleteBySn(posSn);
        }
        System.out.println(jsonObject);
        return AjaxResult.success("更新绑定状态成功！");
    }

    @PostMapping("/fee")
    public AjaxResult fee(@RequestBody JSONObject jsonObject) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
        String posSn=jsonObject.getString("posSn");
        String externalCustomerNo=jsonObject.getString("externalCustomerNo");
        String time=jsonObject.getString("time");
        String amount=jsonObject.getString("amount").split("\\.")[0];
        String host_date = jsonObject.getString("time");  //收取日期
        String mamount_id = IdWorker.getIdStr(); //费用ID(隐藏)
        String merchant_no = jsonObject.getString("externalCustomerNo");  //系统商户编号
        String sn = jsonObject.getString("posSn");  //SN
        String simcardfee = amount;  //收取费用
        String mamount_starts = "1";  //状态(0-初始 1-成功 2-取消 3-待收取 9-未知)
        String amt_type = "0";  //费用类型（0-流量费 1-设备款）
        String creatdate = jsonObject.getString("time");  //创建日期
        String deptName=bizPosMachineStatusRecordsMapper.selectDeptNameByPosCode(posSn);
        BizFeesCharged bizFeesCharged = new BizFeesCharged();
        bizFeesCharged.setMamountId(mamount_id);
        bizFeesCharged.setOrgnname(deptName);
        bizFeesCharged.setMerchantNo(merchant_no);
        bizFeesCharged.setSn(sn);
        bizFeesCharged.setSimcardfee(simcardfee);
        bizFeesCharged.setMamountStarts(mamount_starts);
        bizFeesCharged.setAmtType(amt_type);
        bizFeesCharged.setCreatdate(creatdate);
        bizFeesCharged.setHostDate(sdf1.format(sdf.parse(host_date)));
        bizFeesCharged.setUuid(IdWorker.getIdStr());
        bizFeesCharged.setRmbStatus("1"); //未发放
        BizFeesCharged byId = bizFeesChargedService.getLklLlf(bizFeesCharged);
        if (byId == null) {
            System.out.println(mamount_id);
            //存储流量费收取列表
            bizFeesChargedService.insertBizFeesCharged(bizFeesCharged);
            //判断是第几次收取,  第二次及以后收取不发放, 根据商户判断  且不区分是谁家  辉哥定的 --20250108131500
            try {
                int simAmtCount = bizFeesChargedService.selectIsSecondSimAmt(merchant_no,sn);
                if(simAmtCount > 1 ){// 大于1 , 则不返了
                    System.out.println("查询到"+merchant_no+"-sn-"+sn+"已发放过流量费,本次不再发放"+sdf.format(new Date()));
                    return AjaxResult.success();
                }
            }catch (Exception e){
                System.out.println("拉卡拉二次流量费不返现模块处理存在问题:"+e.getMessage()+"时间:"+sdf.format(new Date()));
            }
            BizFeesCharged bizFeesCharged1 = new BizFeesCharged();
            bizFeesCharged1.setMamountId(bizFeesCharged.getMamountId());
            bizFeesCharged1.setRmbStatus("2"); //发放完成
            bizFeesChargedService.saveOrUpdate(bizFeesCharged1);
            //发放流量费
            SynchronizationDataDTO sy = new SynchronizationDataDTO();
            sy.setSim_amt(Integer.parseInt(bizFeesCharged.getSimcardfee()));
            sy.setPos_sn(bizFeesCharged.getSn());
            sy.setHost_date(sdf.format(new Date()));
            sy.setUuid(bizFeesCharged.getUuid());
            sy.setMerchant_no(bizFeesCharged.getMerchantNo());
            bizTransactionAmount.returnSimAmt(sy, false);
        }
        return AjaxResult.success();
    }

}
